import React, { useState } from "react";
import "./step4.css";
import Index from "../../../components/bg";
import { useNavigate } from "react-router";
import { ROLES } from '../../../config/permissions';

const Step4 = () => {
  // 从本地存储初始化邮箱列表，如果没有则使用空数组
  const [emails, setEmails] = useState(() => {
    const savedEmails = localStorage.getItem("teamMembers");
    return savedEmails ? JSON.parse(savedEmails) : [""];
  });

  const [errors, setErrors] = useState({});

  const navigate = useNavigate();

  const addEmailField = () => {
    if (emails.length >= 10) {
      alert("最多只能邀请10个成员");
      return;
    }
    const newEmails = [...emails, ""];
    setEmails(newEmails);
    localStorage.setItem("teamMembers", JSON.stringify(newEmails));
  };

  // 更详细的邮箱验证函数
  const validateEmail = (email) => {
    // 基本格式验证
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

    if (!email.trim()) {
      return { isValid: false, message: "邮箱不能为空" };
    }

    if (email.length > 254) {
      return { isValid: false, message: "邮箱长度不能超过254个字符" };
    }

    if (!emailRegex.test(email)) {
      return { isValid: false, message: "邮箱格式不正确" };
    }

    // 检查特殊规则
    const localPart = email.split("@")[0];
    const domain = email.split("@")[1];

    if (localPart.length > 64) {
      return { isValid: false, message: "邮箱用户名部分不能超过64个字符" };
    }

    if (localPart.startsWith(".") || localPart.endsWith(".")) {
      return { isValid: false, message: "邮箱用户名不能以点号开始或结束" };
    }

    if (localPart.includes("..")) {
      return { isValid: false, message: "邮箱用户名不能包含连续的点号" };
    }

    // 检查常见的域名错误
    const commonTypos = {
      gmial: "gmail",
      gmai: "gmail",
      gamil: "gmail",
      hotmai: "hotmail",
      homtail: "hotmail",
      yahoocom: "yahoo.com",
    };

    for (const [typo, correct] of Object.entries(commonTypos)) {
      if (domain.includes(typo)) {
        return {
          isValid: false,
          message: `邮箱域名可能输入错误，您是想输入 ${correct} 吗？`,
        };
      }
    }

    return { isValid: true, message: "" };
  };

  const handleEmailChange = (index, value) => {
    const newEmails = [...emails];
    newEmails[index] = value;
    setEmails(newEmails);

    // 实时验证（可选）
    const validation = validateEmail(value);
    if (!validation.isValid) {
      setErrors((prev) => ({
        ...prev,
        [index]: validation.message,
      }));
    } else {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[index];
        return newErrors;
      });
    }

    localStorage.setItem("teamMembers", JSON.stringify(newEmails));
  };

  const removeEmailField = (index) => {
    const newEmails = emails.filter((_, i) => i !== index);
    setEmails(newEmails);
    localStorage.setItem("teamMembers", JSON.stringify(newEmails));
  };

  const handleSubmit = () => {
    const newErrors = {};
    let hasError = false;

    // 验证邮箱
    emails.forEach((email, index) => {
      const validation = validateEmail(email);
      if (!validation.isValid) {
        newErrors[index] = validation.message;
        hasError = true;
      } else if (emails.indexOf(email) !== index) {
        newErrors[index] = "邮箱地址重复";
        hasError = true;
      }
    });

    setErrors(newErrors);

    if (!hasError) {
      const teamData = {
        members: emails
          .filter((email) => email.trim() !== "")
          .map((email) => ({
            email,
            role: ROLES.MEMBER,
            position: "普通员工",
            invitedAt: new Date().toISOString(),
            status: "pending",
          })),
        createdAt: new Date().toISOString(),
      };

      localStorage.setItem("teamData", JSON.stringify(teamData));
      navigate("/success");
    }
  };

  return (
    <div className="register-container">
      <Index />
      <div className="register-headers">
        <span className="step-text">STEP 4/4</span>
        <h4>邀请团队成员</h4>
        <div className="email-list">
          {emails.map((email, index) => (
            <div key={index} className="email-input-group">
              <input
                type="email"
                value={email}
                placeholder="youliao@gmail.com"
                onChange={(e) => handleEmailChange(index, e.target.value)}
                className={errors[index] ? "error" : ""}
              />
              {errors[index] && (
                <div className="error-message">{errors[index]}</div>
              )}
              {index > 0 && (
                <button
                  className="remove-btn"
                  onClick={() => removeEmailField(index)}
                >
                  ×
                </button>
              )}
            </div>
          ))}
        </div>
        <button className="add-email-btn" onClick={addEmailField}>
          + 继续添加
        </button>
      </div>

      <div className="button-group">
        <button className="btn-prev" onClick={() => navigate("/step3")}>
          ← 上一步
        </button>
        <button className="btn-next" onClick={handleSubmit}>
          下一步 →
        </button>
      </div>
    </div>
  );
};

export default Step4;
